/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.Course;
import models.Payment;
import models.User;
import models.Bean;
import org.hibernate.Session;
import service.CategoryDao;
import service.CourseDao;
import service.HibernateUtil;
import service.PaymentDao;
import service.UserDao;

/**
 *
 * @author kjeld
 */
public class StudentCourseController extends HttpServlet {

    private HibernateUtil HU = new HibernateUtil();
    private Session session = HU.openSession();
    private CourseDao dao = new CourseDao(session);
    private UserDao udao = new UserDao(session);
    private PaymentDao pdao = new PaymentDao(session);
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        long userID = 0;
        HttpSession sessie = request.getSession(true);
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals("userID")) {
                if (cookie.getValue().length() > 0) {
                    userID = Long.parseLong(cookie.getValue());
                    sessie.setAttribute("loggedin", "true");
                }
            }
        }
        if (userID != 0) {
            User user = udao.get(userID);
            //System.out.println(Currency.getInstance(new Locale("hi", "IN")).getSymbol());
            String country = user.getCountry();
            Locale list[] = SimpleDateFormat.getAvailableLocales();
            Locale userLocale = null;
            //System.out.println("Country: " + country);
            for(Locale locale : list){
                if(locale.getDisplayCountry().equals(country)){
                    System.out.println("ja");
                    userLocale = locale;
                }
            }
            Course course = dao.get(Long.parseLong(request.getParameter("courseID")));
            sessie.setAttribute("user", user);
            sessie.setAttribute("course", course);
            if(userLocale != null){
                Currency currency = Currency.getInstance(userLocale);
                //System.out.println("user locale: " + userLocale.getDisplayCountry());
                //System.out.println("valuta:\nCode: " + Currency.getInstance(userLocale).getCurrencyCode() + "\nNaam: " + Currency.getInstance(userLocale).getDisplayName());
                
                if(currency.getCurrencyCode().equals("EUR")){
                    String price = getPrice(currency, course.getPrice(), userLocale);
                    sessie.setAttribute("price", price);
                } else {
                    sessie.setAttribute("price", course.getPrice());
                }
                sessie.setAttribute("symbol", currency.getSymbol(userLocale));
                sessie.setAttribute("currency", currency);
            }
            RequestDispatcher dispatcher = request.getRequestDispatcher("addcourse.jsp");
            dispatcher.forward(request, response);
        } else {
            response.sendRedirect("/index");
        }
    }
    
    private String getPrice(Currency currency, double amount, Locale locale){
        NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);
        DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.LONG,
                                       locale);
        
        //String am = price.replaceAll("[.]", "");
        //String amount = am.replaceAll(",", ".");
/*        
        //-- check for numbers and point, komma only
        if(!amount.matches("[0-9.,]+")){
            System.out.println("Please enter a valid amount");
        }
*/      
        String url = "http://finance.yahoo.com/q/bc?s=EUR" + currency.getCurrencyCode();
        String price = "";
        try {
            // Fetch results from Yahoo
            String results = "";
            URL resultPage = new URL(url);
            BufferedReader in = new BufferedReader(new InputStreamReader(resultPage.openStream()));

            String inputLine;

            while ((inputLine = in.readLine()) != null) {
              // Process each line.
              results = results + inputLine;
            }
            
            in.close();
            
            // Parrent matching
            Pattern finalPattern = Pattern.compile("x\">([0-9.,]+)</span>");
            Matcher matchFind = finalPattern.matcher(results);
            matchFind.find();
            
            double curRate = Double.valueOf(matchFind.group(1)).doubleValue();
            double totalConvert = curRate * Double.valueOf(amount).doubleValue();

            //-- shows amount in GBP
            System.out.println(String.format("Valuta in "+currency.getCurrencyCode()+": " + "%,.2f", totalConvert));
            System.out.println(currencyFormatter.format(totalConvert));
            price = String.format("%,.2f", totalConvert);
            
       } catch (Exception e) {
            //-- shows error message when try contains errors
            System.out.println( e.getMessage());
       }
        return price;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        long userID = 0;
        long courseID = 0;
        long bankNumber = 0;
        Date payDate = new Date();
        double price = 0.0;
        
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals("userID")) {
                if (cookie.getValue().length() > 0) {
                    userID = Long.parseLong(cookie.getValue());
                }
            }
        }
        
        if (request.getParameter("courseID") != null) {
            courseID = Long.parseLong(request.getParameter("courseID"));
        }
        
        Course course = dao.get(courseID);
        courseID = course.getCourseID();
        price = course.getPrice();
        if (request.getParameter("banknumber") != null) {
            bankNumber = Long.parseLong(request.getParameter("banknumber"));
        }
        
        if (courseID != 0 && userID != 0) {
            Payment payment = new Payment(payDate, userID, courseID, bankNumber, price);
            pdao.save(payment);
            User user = udao.get(userID);
            user.addStudentCourse(course);
            course.getUsers().add(user);
            udao.update(user);
            String address = "/succespayment.jsp";
            response.sendRedirect(address);
        }

        //forward(request, response, null);
    }
}
